package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    /*
        登录
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){
        //1.根据用户名去查询一个employee对象
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee empForMysql = employeeService.getOne(queryWrapper);
        //2.1 员工是空，失败
        if(empForMysql==null){
            return R.error("用户名不存在");
        }
        //2.2员工状态是0，失败
        if(empForMysql.getStatus()==0){
            return R.error("用户被禁用");
        }
        //2.3员工的密码对应不上也失败
        String salt = empForMysql.getPassword().substring(32);
        String miwen = DigestUtils.md5DigestAsHex((employee.getPassword() + salt).getBytes()) + salt;
        if(!miwen.equals(empForMysql.getPassword())){
            return R.error("密码错误");
        }

        //什么才算登录？session中有用户对象，才算登录。
        request.getSession().setAttribute("employee",empForMysql);
        //3 登录成功
        return R.success(empForMysql);
    }

    /*
        退出
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        //request.getSession().removeAttribute("employee");
        request.getSession().invalidate();//销毁当前浏览器对应的session
        return R.success(null);
    }

    /*
        添加员工
     */
    @PostMapping
    public R save(@RequestBody Employee employee,HttpServletRequest req){
        //完善employee的数据
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());//从没有修改成有

//        Employee empForSession = (Employee) req.getSession().getAttribute("employee");
//        employee.setCreateUser(empForSession.getId());
//        employee.setUpdateUser(empForSession.getId());
        String salt = UUID.randomUUID().toString().replace("-", "");
        String md5Password = DigestUtils.md5DigestAsHex(("123456" + salt).getBytes()) + salt;
        employee.setPassword(md5Password);//默认密码
        //保存
       /* try {
        } catch (Exception e) {
            return R.error("用户名不能重复");
        }*/
        //总结：后台不管报不报错，都必须给用户返回一个R对象
        employeeService.save(employee);
        return R.success(null);
    }

    /*
        分页查询:
            1.如果没有传递name就是普通分页
            2.如果传递了name就是带条件的分页
        注意事项：因为id是long类型，到达前端之后就会产生精度损失。
        解决：让long类型的数字id，返回给前端之前，变成String类型的id
        {id:1527386273283243} 会产生精度损失
        {id:"1527386273283243"} 不会产生精度损失

     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        //创建一个分页条件对象，这个对象即是分页条件，又是pageBean
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);// name like "%name%"
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //2条sql 查询出list，查询出total，把结果封装到pageInfo
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /*
        启用禁用
        修改用户
        三合一功能
     */
    @PutMapping
    public R update(@RequestBody Employee employee,HttpServletRequest req){
        log.info("EmployeeController类中此时的线程id为：{}", Thread.currentThread().getId());

        //完善数据
//        Employee empForSession = (Employee) req.getSession().getAttribute("employee");
//        employee.setUpdateUser(empForSession.getId());
//        employee.setUpdateTime(LocalDateTime.now());
        //update employee set status =? where id = ?
        //UPDATE employee SET username=?, name=?, password=?, phone=?, sex=?, id_number=?, status=?,
        // create_time=?, update_time=?, create_user=?, update_user=? WHERE id=?
        employeeService.updateById(employee);
        //当修改的对象，数据不完整的时候，会不会把null值修改进表中，不会。
        return R.success(null);
    }

    /*
        修改回显操作
     */
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        Employee emp = employeeService.getById(id);
        return R.success(emp);
    }
}

